package com.openswimsoftware.orm.model.query;

import java.util.Locale;

import com.openswimsoftware.orm.ORM;
import com.openswimsoftware.orm.model.Model;

import android.content.Context;
import android.util.Log;

public class ModelDelete<E extends  Model<E>> extends ModelQuery<E, ModelDelete<E>> {
	
	public ModelDelete(Context context, Class<E> modelType, E model)
	{
		super(context, modelType, model);
	}
	
	public boolean execute()
	{
		this.dbInterface.openDB();
		
		String table = ORM.tableName(this.modelType);
		
		if (this.model.getId() > -1)
		{
			String where = "_ID = ?";
			String[] whereArgs = new String[]{ this.model.getId()+"" };
			
			Log.d("orm", "Deleting " + this.modelType.getSimpleName() + " with id " + this.model.getId()+"");
			
			int num = this.dbInterface.getDB().delete(table, where, whereArgs);
			
			this.dbInterface.closeDB();
			
			return (num > 0);
		}
		else if (this.model.getParentId() > -1)
		{
			String where = "_" + this.model.getParentName().toUpperCase(Locale.US) + "_ID = ?";
			String[] whereArgs = new String[]{ this.model.getParentId()+"" };
				
			Log.d("orm", "Deleting " + this.modelType.getSimpleName() + " with parent id " + this.model.getParentId()+"");
			
			int num = this.dbInterface.getDB().delete(table, where, whereArgs);
			
			this.dbInterface.closeDB();
			
			return (num > 0);
		}
		
		return false;
			
	}
	
}
